/**
 *
 */
package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnScrollChangedListener;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.RadioCategoryGridViewAdapter;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.AlbumCollectionItem;
import com.jdy.haoduoai.model.AlbumItem;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.RadioCategoryItem;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.util.ACache;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.DateUtils;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ImageLoader;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.HorizontalIndicator;
import com.jdy.haoduoai.view.MyGridView;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author zp 2016-4-13 下午9:32:38
 */
public class RadioStationActivity extends BaseActivity {

    private LeUser mLeUser;

    private Handler mHandler;

    @InjectView(id = R.id.icon_img)
    private ImageView mRecommendImg;

    @InjectView(id = R.id.catelog_title_tv)
    private TextView mRecommendTv;

    @InjectView(id = R.id.more_img)
    private ImageView mMoreImg;

    @InjectView(id = R.id.h_layout)
    private LinearLayout mHRootLayout;

    @InjectView(id = R.id.scenery_first_layout)
    private LinearLayout mSceneryFirstLayout;

    @InjectView(id = R.id.scenery_second_layout)
    private LinearLayout mScenerySecondLayout;

    @InjectView(id = R.id.age_range_first_layout)
    private LinearLayout mAgeRangeFirstLayout;

    @InjectView(id = R.id.age_range_second_layout)
    private LinearLayout mAgeRangeSecondLayout;

    @InjectView(id = R.id.bottom_gridview)
    private MyGridView mBottomGridView;

    @InjectView(id = R.id.h_scrollview, click = true)
    private HorizontalScrollView h_scrollview;
    @InjectView(id = R.id.h_indicator, click = true)
    private HorizontalIndicator h_indicator;

    private List<AlbumCollectionItem> mSceneryList;

    private List<AlbumCollectionItem> mAgeRangeList;

    private List<RadioCategoryItem> mRadioCategoryList;

    private RadioCategoryGridViewAdapter mRCGVAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.radio_station_layout);

        setTitle("宝宝故事机");
        mLeUser = ((LeXiaoXiaoBanApp) this.getApplication()).getUser();
        mHandler = new Handler();
        mCache = ACache.get(this);

        init();
    }

    @SuppressWarnings("unchecked")
    private void init() {
        mSceneryList = new ArrayList<AlbumCollectionItem>();
        mAgeRangeList = new ArrayList<AlbumCollectionItem>();
        mRadioCategoryList = new ArrayList<RadioCategoryItem>();
        mRecommendImg.setImageResource(R.drawable.extra_ordinary_icon);

        mRecommendTv.setText("精彩推荐");
        mMoreImg.setVisibility(View.GONE);
        h_scrollview.getViewTreeObserver().addOnScrollChangedListener(
                new OnScrollChangedListener() {
                    @Override
                    public void onScrollChanged() {
                        int deltaX = h_scrollview.getScrollX();
                        DisplayMetrics metrics = getResources().getDisplayMetrics();
                        int maxX = h_scrollview.getChildAt(0).getMeasuredWidth()
                                - metrics.widthPixels + 5;
                        h_indicator.onScrollChanged(deltaX, maxX);
                    }
                });

        String dataRecommend = mCache.getAsString("RadioStationActivityRecommend");
        if (Tools.isNotEmpty(dataRecommend)) { // 有缓存
            // ObjectMapper mapper = new ObjectMapper();

            // List<AlbumItem> recommendAlbums = Arrays.asList(mapper.readValue(
            // dataRecommend, AlbumItem[].class));

            List<AlbumItem> recommendAlbums = (List<AlbumItem>) JsonSerializer
                    .getInstance().deserialize(dataRecommend, ArrayList.class,
                            AlbumItem.class);
            if (Tools.isNotEmpty(recommendAlbums)) {
                setRecommendView(recommendAlbums);
            }

            loadCategoryData();
        } else {
            loadRecommendationData();
        }
    }

    private ACache mCache;

    private void playvideo(final int sid, final String status) {
        new CustomAsyncTask(this, new IAsyncTask() {
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {
                if (result.isSuccess()) {
                    DateUtils.showToast(RadioStationActivity.this, "已推送到设备播放");
//          if (LeConfig.isDeviceConnect) {
//            DateUtils.showToast(RadioStationActivity.this, "已推送到设备播放");
//          } else {
//            DateUtils.showToast(RadioStationActivity.this, "未连接到设备，请检查设备联网情况！");
//          }

                } else {
                    LeConfig.isDeviceConnect = false;
                    DateUtils.showToast(RadioStationActivity.this, "设备不在线");
                }
                // if (result.isSuccess()) {
                // // if (("cartoon").equals(status) || ("continue").equals(status)) {
                // // toastShow("推送成功");
                // // isPlay = true;
                // // // playbutton.setBackgroundResource(R.drawable.pause_icon);
                // // } else if (("pause").equals(status)) {
                // // toastShow("暂停播放");
                // // isPlay = false;
                // // // playbutton.setBackgroundResource(R.drawable.ico_play);
                // // } else {
                // // toastShow(result.data);
                // // }
                // } else {
                // toastShow(result.data);
                // }
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {

                HashMap<String, Object> param_ = new HashMap<String, Object>();

                int uid = -1, volume = -1, minutes = -1;
                param_.put(HttpUtils.TAG_SNO_I, mGlobalLeUser.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                param_.put(HttpUtils.TAG_ACTION_I, "play");
                param_.put(HttpUtils.TAG_OPERATION_I, "cartoon");
                param_.put(HttpUtils.TAG_TYPE_I, "cartoon");
                //  param_.put("mode", "im");

                if (sid != -1) {
                    param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
                }

                param_.put(HttpUtils.TAG_PLAY_MODE, String.valueOf(LeConfig.PlayMode));

                return HttpUtils.startRequest(HttpUtils.API_URL
                                + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
                        HttpUtils.TAG_GET_REQUEST);

            }
        }).execute();
    }

    private ImageLoader mImageLoader;

    @SuppressLint("InflateParams")
    private void setRecommendView(List<AlbumItem> aiList) {
        int i = 0;
        int size = aiList.size();
        for (; i < size; i++) {
            final AlbumItem ai = aiList.get(i);
            View hChild = LayoutInflater.from(this).inflate(
                    R.layout.horizontallist_item, null);
            final ImageView coverImg = (ImageView) hChild.findViewById(R.id.img);
            ImageView playStateImg = (ImageView) hChild
                    .findViewById(R.id.play_state_img);
            coverImg.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    playvideo(ai.id, "radio");
                }
            });
            coverImg.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
            TextView titleTv = (TextView) hChild.findViewById(R.id.tittle);
            titleTv.setText(ai.title);
            if (Tools.isNotEmpty(ai.album_cover))
                Picasso.with(this).load(ai.album_cover).fit().centerCrop()
                        .placeholder(getResources().getDrawable(R.drawable.default_cover))
                        .error(getResources().getDrawable(R.drawable.default_cover))
                        .into(coverImg, new Callback() {

                            @Override
                            public void onSuccess() {
                                // TODO Auto-generated method stub

                            }

                            @Override
                            public void onError() {
                                if (mImageLoader == null) {
                                    mImageLoader = new ImageLoader(RadioStationActivity.this);
                                }
                                mImageLoader.DisplayImage(ai.album_cover, coverImg, false);

                            }
                        });
            LayoutParams params_image = new LayoutParams(
                    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
            params_image.setMargins(Tools.getPixelByDip(this, 5), 0,
                    Tools.getPixelByDip(this, 5), 0);
            hChild.setLayoutParams(params_image);
            // playStateImg.setVisibility(View.VISIBLE);
            // if (ai.length % 2 == 0) {
            // playStateImg.setImageResource(R.drawable.finish_recom_icon);
            // }
            mHRootLayout.addView(hChild);
        }
    }

    private void loadRecommendationData() {
        new CustomAsyncTask(this, new IAsyncTask() {
            @SuppressWarnings("unchecked")
            @Override
            public void onRecieveData(Activity activity, ResponseResult result) {

                Log.i("test", "请求到的数据结果是:" + result.isSuccess());

                if (result.isSuccess()) {
                    mCache.remove("RadioStationActivityRecommend");
                    mCache.put("RadioStationActivityRecommend", result.data,
                            2 * ACache.TIME_DAY);

                    List<AlbumItem> recommendAlbums = (List<AlbumItem>) JsonSerializer
                            .getInstance().deserialize(result.data, ArrayList.class,
                                    AlbumItem.class);
                    if (Tools.isNotEmpty(recommendAlbums)) {
                        setRecommendView(recommendAlbums);
                    }

                }

                loadCategoryData();
            }

            @Override
            public ResponseResult doInbackground(Activity activity) {

                Log.i("test", "AAAA");

                if (mLeUser == null) {
                    mLeUser = Tools.restoreLeUser();
                }

                HashMap<String, Object> param_ = new HashMap<String, Object>();
                param_.put("sno", mLeUser.sno);
                param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                return HttpUtils.startRequest(HttpUtils.API_URL
                                + "/api/2.0/catalog/radio/recommand", param_,
                        HttpUtils.TAG_GET_REQUEST);

            }
        }).execute();
    }

    private TextView addButton(int bgRid, int textColor) {
        TextView btn = new TextView(this);
        btn.setBackgroundResource(bgRid);
        LayoutParams params = new LayoutParams(0,
                LayoutParams.MATCH_PARENT);
        params.weight = 1;
        // int margin = Tools.getPixelByDip(this, 6);
        // params.setMargins(0, margin, 0, margin);
        btn.setGravity(Gravity.CENTER);
        btn.setLayoutParams(params);
        btn.setTextColor(textColor);
        return btn;
    }

    private TextView addSceneryButton(String caption, final int id, int i) {
        TextView btn = addButton(R.drawable.green_vertical_right_button_bg,
                Color.argb(255, 135, 201, 91));

        btn.setText(caption);
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(RadioStationActivity.this, StoryDetailActivity.class);
                intent.putExtra("id", id);
                startActivity(intent);
            }
        });
        return btn;
    }

    private TextView addAgeRangeButton(String caption, final int id) {
        TextView btn = addButton(R.drawable.purple_vertical_right_button_bg,
                Color.argb(255, 72, 112, 171));
        btn.setText(caption);
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(RadioStationActivity.this, StoryDetailActivity.class);
                intent.putExtra("id", id);
                startActivity(intent);
            }
        });
        return btn;
    }

    /**
     * 解析Json数据
     *
     * @param data
     */
    private void parseJsonArray(String data) {
        try {
            JSONArray jsonArray = new JSONArray(data);
            int size = jsonArray.length();
            mRadioCategoryList.clear();
            for (int i = 0; i < size; i++) {
                JSONObject jo = (JSONObject) jsonArray.get(i);
                String name = jo.getString("name");
                if (name.equals("情景")) {
                    mSceneryList.clear();

                    mSceneryList = (List<AlbumCollectionItem>) JsonSerializer
                            .getInstance().deserialize(jo.getString("albums"),
                                    ArrayList.class, AlbumCollectionItem.class);

                } else if (name.equals("年龄")) {
                    mAgeRangeList.clear();

                    mAgeRangeList = (List<AlbumCollectionItem>) JsonSerializer
                            .getInstance().deserialize(jo.getString("albums"),
                                    ArrayList.class, AlbumCollectionItem.class);
                } else {
                    if (!"金牌新概念".equals(name) && !"课文朗读".equals(name)) {
                        RadioCategoryItem rci = JsonSerializer.getInstance().deserialize(
                                jo.toString(), RadioCategoryItem.class);
                        mRadioCategoryList.add(rci);
                    }
                }
            }

            setSceneryView();
            setAgeRangeView();
            setRadioCategoryView();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mHRootLayout.requestFocus();
    }

    private void setRadioCategoryView() {
        mRCGVAdapter = new RadioCategoryGridViewAdapter(this, mRadioCategoryList);
        mBottomGridView.setAdapter(mRCGVAdapter);
    }

    private void setAgeRangeView() {
        if (mAgeRangeList.size() != 0) {
            int i = 0;
            int size = mAgeRangeList.size();
            for (; i < size; i++) {
                AlbumCollectionItem aci = mAgeRangeList.get(i);
                TextView btn = addAgeRangeButton(aci.getName(), aci.getId());
                if (i < 4) {
                    mAgeRangeFirstLayout.addView(btn);
                } else {
                    mAgeRangeSecondLayout.addView(btn);
                }
            }
        }
    }

    private void setSceneryView() {
        if (mSceneryList.size() != 0) {
            int i = 0;
            int size = mSceneryList.size();
            for (; i < size; i++) {
                AlbumCollectionItem aci = mSceneryList.get(i);
                TextView btn = addSceneryButton(aci.getName(), aci.getId(), i);
                if (i < 4) {
                    mSceneryFirstLayout.addView(btn);
                } else {
                    mScenerySecondLayout.addView(btn);
                }
            }
        }
    }

    /**
     * 获取页面数据
     */
    private void loadCategoryData() {
        String data = mCache.getAsString("RadioStationActivityloadCategoryData");
        if (Tools.isNotEmpty(data)) {
            parseJsonArray(data);
        } else {
            new CustomAsyncTask(this, new IAsyncTask() {
                @Override
                public void onRecieveData(Activity activity, ResponseResult result) {
                    if (result.isSuccess()) {
                        if (Tools.isNotEmpty(result.data)) {
                            mCache.remove("RadioStationActivityloadCategoryData");
                            mCache.put("RadioStationActivityloadCategoryData", result.data,
                                    2 * ACache.TIME_DAY);

                            parseJsonArray(result.data);
                        }
                    }
                }

                @Override
                public ResponseResult doInbackground(Activity activity) {

                    if (mLeUser == null) {
                        mLeUser = Tools.restoreLeUser();
                    }

                    HashMap<String, Object> param_ = new HashMap<String, Object>();
                    param_.put("sno", mLeUser.sno);
                    param_.put("t_cate", "1");
                    param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

                    Log.i("test", HttpUtils.API_URL
                            + "/api/2.0/catalog/radio/collection?" + "sno=" + mLeUser.sno + "&" + HttpUtils.TAG_KEY_I + "=" + HttpUtils.KEY);

                    return HttpUtils.startRequest(HttpUtils.API_URL
                                    + "/api/2.0/catalog/radio/collection", param_,
                            HttpUtils.TAG_GET_REQUEST);

                }
            }).execute();
        }

    }

}
